<template>
  <div class="schedule-config__wrapper">
    <div class = 'schedule-config__center'>
      <div class="schedule-config-wrap">
        <search
          :inputTitle="'请输入服务号或日程名称进行搜索'"
          @turnPage="turnPage"
          :currentPage="currentPage"
          :count="count"
          @exportMethod="exportAct"
          @inputChange = 'handleIconClick'
          :pageSize="pageSize"
          :showAdd="false"
          :disabledReload = "disabledReload"></search>
        <scheduleTab :tableData="tableData" @updata="updata" @del="del" @add="add" :loading="tableLoading" ref="scheduleTable"></scheduleTab>
      </div>
    </div>
    <leftSlide :visible.sync='leftSlideVisible'  :title = 'slideLeftTitle' >
          <editSchedule v-if="isShowEdit"
                        ref="editSch"
                       :tableData="editData"
                       :editScheduleInfo="editScheduleInfo"
                       @editRefresh="editRefresh" @cancelClick = 'cancelClick'></editSchedule>
          <addSchedule v-if="isShowAdd"
                       :addScheduleInfo = "addScheduleInfo"
                       @addRefresh="addRefresh" @cancelClick = 'cancelClick'></addSchedule>
    </leftSlide>
  </div>
</template>
<script>
  import leftSlide from '@/components/ui-modules/newConfig/leftSlide.vue'
  import configCompositionTwoWindowStyle from '@/components/ui-modules/config/configCompositionTwoWindowStyle'
  // import search from '@/components/business-modules/config/channelConfig/base/search'
  import search from '../base/search.vue'
  import BreadCrumbConfig from '@/components/ui-modules/breadCrumb/BreadCrumbConfig'
  import scheduleTab from './scheduleTab'
  import editSchedule from './editSchedule.vue'
  import {deepClone, ivrSearch} from '@/utils/m7Utils'
  import addSchedule from './addSchedule'
  export default {
    name: 'schedule',
    data () {
      return {
        name: 'callScheduleManage',
        leftSlideVisible: false,
        disabledReload: true,
        slideLeftTitle: '',
        norSearch: [],
        pageSize: 10,
        PBX: '',
        pbxs: [],
        searchContent: '',
        addScheduleInfo: {},
        reload: true,
        isShowAdd: false,
        isShowEdit: false,
        advSearchData: {
          items: [
            {
              title: '服务号类型',
              type: 'select',
              valueName: 'Type',
              data: [
                {label: '普通', value: 'normal'},
                {label: '轻量级', value: 'lightweight'}
              ]
            },
            {
              title: '服务号',
              type: 'input',
              valueName: 'Exten'
            }
          ],
          form: {Type: '', Exten: ''}
        },
        availableService: [],
        dataList: [],
        count: 0,
        agents: [],
        currentPage: 1,    //   当前页
        tableData: [],           //  表格数据
        tableLoading: false,      //   表格  loading
        isShowAddOrEdit: false,   //   右侧  新建或修改 显隐
        inputName: '',
        editScheduleInfo: {},
        editData: {},
        currentServerNo: ''
      }
    },
    components: {
      addSchedule,
      configCompositionTwoWindowStyle,
      search,
      BreadCrumbConfig,
      scheduleTab,
      editSchedule,
      leftSlide
    },
    computed: {
      Account () {
        return this.$store.state.session.account.account
      },
      currentPBX () {
        return this.$store.state.config.callCenter.currentPBX
      }
    },
    watch: {
      currentPBX () {
        if (this.$route.meta.title === this.name) {
          this.refresh()
        }
      }
    },
    methods: {
      exportAct (val) {
        if (val === 'add') {
          this.add()
        } else if (val === 'refresh') {
          this.refresh()
        } else if (val === 'active') {
          this.active()
        }
      },
      ToChangePBX () {
        this.currentPage = 1
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
        this.tableData = []
        let dataArray = []
        this.norSearch = []
        if (this.searchContent) {
          dataArray = ivrSearch(this.dataList, this.searchContent, ['Exten'])
        } else {
          dataArray = deepClone(this.dataList)
        }
        dataArray.forEach(item => {
          if (this.PBX) {
            if (item.PBX === this.PBX) {
              this.norSearch.push(item)
            }
          } else { // 选择全部时
            this.norSearch.push(item)
          }
        })
        this.tableData = []
        this.handleFakePage(this.norSearch)
        this.count = this.norSearch.length
      },
      handleIconClick (searchContent, flag) {
        if (!(flag === 'search' && this.currentServerNo)) {
          this.currentPage = 1
        }
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
        this.tableData = []
        let dataArray = []
        let ids = []
        this.norSearch = []
        this.searchContent = searchContent
        // if (this.PBX) {
        //   dataArray = ivrSearch(this.dataList, this.PBX, ['PBX'])
        // } else {
        //   dataArray = deepClone(this.dataList)
        // }
        dataArray = deepClone(this.dataList)
        dataArray.forEach(item => {
          if (item.Exten.indexOf(searchContent) !== -1) {
            if (ids.indexOf(item._id) === -1) {
              this.norSearch.push(item)
              ids.push(item._id)
            }
          }
          if (item.SchedulesList && item.SchedulesList.length > 0) {
            item.SchedulesList.forEach((item1) => {
              if (item1.DisplayName.indexOf(searchContent) !== -1) {
                if (ids.indexOf(item._id) === -1) {
                  this.norSearch.push(item)
                  ids.push(item._id)
                }
              }
            })
          }
        })
        this.tableData = []
        this.handleFakePage(this.norSearch)
        this.count = this.norSearch.length
        if (flag === 'search' && this.currentServerNo) {
          this.$nextTick(() => {
            this.$refs.scheduleTable.rowClick({Exten: this.currentServerNo})
          })
        }
      },
//      添加日程
      add (val) {
        this.isShowAddOrEdit = true
        this.isShowEdit = false
        this.leftSlideVisible = true
        this.slideLeftTitle = '日程添加'
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[val.PBX]) {
          this.isShowAdd = true
          this.addScheduleInfo = val
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = val.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            if (res && res.success) {
              this.isShowAdd = true
              this.addScheduleInfo = val
            }
          })
        }
      },
//      修改日程
      updata (val) {
        this.isShowAddOrEdit = true
        this.isShowAdd = false
        this.leftSlideVisible = true
        this.slideLeftTitle = '日程修改'
        if (this.$store.state.session.ivrMap && this.$store.state.session.ivrMap[val.PBX]) {
          this.isShowEdit = true
          this.editScheduleInfo = val
          for (let i = 0; i < this.tableData.length; i++) {
            if (this.tableData[i].Exten === val.ServiceNo) {
              this.editData = deepClone(this.tableData[i])
              this.$nextTick(function () {
                this.$refs.editSch.changeData(this.editScheduleInfo)
                this.$refs.editSch.ToChangePeer(this.editScheduleInfo.ToPeerType)
              })
            }
          }
        } else {
          let data = {}
          data.Account = this.$store.state.session.account.account
          data.PBX = val.PBX
          this.$store.dispatch('getAllNodesByPbxForSkill', data).then(res => {
            this.isShowEdit = true
            this.editScheduleInfo = val
            for (let i = 0; i < this.tableData.length; i++) {
              if (this.tableData[i].Exten === val.ServiceNo) {
                this.editData = deepClone(this.tableData[i])
                this.$nextTick(function () {
                  this.$refs.editSch.changeData(this.editScheduleInfo)
                  this.$refs.editSch.ToChangePeer(this.editScheduleInfo.ToPeerType)
                })
              }
            }
          })
        }
      },
//      高级搜索
      advSearch (val) {
        this.inputName = ''
        let data = {}
        data.Account = this.$store.state.session.account.account
        val.Type && (data.Type = val.Type)
        val.Exten && (data.Exten = val.Exten)
        val.PBX && (data.PBX = val.PBX)
        this.search(data)
      },
//      添加日程成功刷新
      addRefresh (data) {
        // this.searchContent = ''
        this.disabledReload = false
        this.leftSlideVisible = false
        this.refresh(data)
      },
      roloadIvrSucc () {
        this.disabledReload = true
      },
      editRefresh (data) {
        this.leftSlideVisible = false
        this.disabledReload = false
        this.refresh(data)
      },
//      刷新
      refresh (data) {
        // this.searchContent = ''
        this.isShowAddOrEdit = false
        this.isShowAdd = false
        this.isShowEdit = false
        this.PBX = this.currentPBX
        this.search({Account: this.$store.state.session.account.account}, {Account: this.$store.state.session.account.account}, data)
      },
//      input 搜索
      searchByName (val) {
        console.log(val)
        this.inputName = val
        this.norSearch = ivrSearch(this.dataList, val, ['Exten'])
        this.tableData = []
        for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < this.norSearch.length; i++) {
          this.tableData.push(this.norSearch[i])
        }
        this.count = this.norSearch.length
      },
//      初始化数据
      search (data1, data2, serviceNo) {
        // this.currentPage = 1
        this.tableData = []
        let _pageList = []
        this.tableLoading = true
        data1.PBX = this.currentPBX
        data2.PBX = this.currentPBX
        let p1 = this.$store.dispatch('queryServiceNo', data1)
        let p2 = this.$store.dispatch('querySchedule', data2)
        Promise.all([p1, p2]).then(([resp1, resp2]) => {
          if (resp1.success && resp2.success) {
            this.tableData = []
            if (resp1.list) {
              resp1.list.forEach(item => {
                if (item.Type === 'normal') {
                  let obj = {
                    Account: item.Account,
                    PBX: item.PBX,
                    Exten: item.Exten,
                    DisplayName: item.DisplayName,
                    Schedules: item.Schedules,
                    ToPeer: item.ToPeer,
                    Type: item.Type,
                    UpdateTime: item.UpdateTime,
                    UpdateUser: item.UpdateUser,
                    _id: item._id,
                    SchedulesList: []
                  }
                  _pageList.push(obj)
                }
              })
              this.count = _pageList.length
              if (resp2.list) {
                _pageList.forEach((item1, index1) => {
                  resp2.list.forEach((item2, index2) => {
                    if ((item1.Exten === item2.ServiceNo) && (item1.PBX === item2.PBX)) {
                      _pageList[index1].SchedulesList.push(item2)
                    }
                  })
                })
              }
            }
          }
          this.dataList = []
          for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < _pageList.length; i++) {
            this.tableData.push(_pageList[i])
          }
          this.dataList = deepClone(_pageList)
          if (serviceNo) {
            this.$nextTick(() => {
              this.$refs.scheduleTable.rowClick({Exten: serviceNo})
            })
            this.currentServerNo = serviceNo
          }
          if (this.searchContent) {
            this.handleIconClick(this.searchContent, 'search')
          }
        })
      },
      handleFakePage (_array) {
        for (let i = (this.currentPage - 1) * 10; i < this.currentPage * 10 && i < _array.length; i++) {
          this.tableData.push(_array[i])
        }
      },
      turnPage (val) {
        this.currentPage = val
        this.tableData = []
        if (this.searchContent === '') {
          this.handleFakePage(this.dataList)
        } else {
          this.handleFakePage(this.norSearch)
        }
      },
//      删除日程
      del (_schedule) {
        console.log(_schedule)
        let data = {
          ServiceNo: _schedule.ServiceNo,
          DisplayName: _schedule.DisplayName,
          Order: _schedule.Order,
          StartDate: _schedule.StartDate,
          EndDate: _schedule.EndDate,
          StartTime: _schedule.StartTime,
          EndTime: _schedule.EndTime,
          WeekMon: _schedule.WeekMon,
          WeekTue: _schedule.WeekTue,
          WeekWed: _schedule.WeekWed,
          WeekThu: _schedule.WeekThu,
          WeekFri: _schedule.WeekFri,
          WeekSat: _schedule.WeekSat,
          WeekSun: _schedule.WeekSun,
          ToPeer: _schedule.ToPeer,
          ToPeerType: _schedule.ToPeerType,
          IvrProcessId: _schedule.IvrProcessId,
          Account: _schedule.Account,
          PBX: _schedule.PBX,
          AnnouncementId: _schedule.AnnouncementId,
          _id: _schedule._id
        }
        this.$confirm('确定要删除该日程吗？', this.$t('public.tip'), {
          confirmButtonText: this.$t('public.confirm'),
          cancelButtonText: this.$t('public.cancel'),
          cancelButtonClass: 'primary_btn',
          confirmButtonClass: 'primary_btn',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('deleteSchedule', data).then(res => {
            if (res && res.success) {
              this.refresh(_schedule.ServiceNo)
              this.disabledReload = false
              this.$message({
                message: '成功删除！',
                type: 'success'
              })
            } else {
              this.$message.error('删除失败！')
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('public.cancel')
          })
        })
      },
      active () {
        let obj = {}
        obj.PBX = this.currentPBX
        obj.Account = this.Account
        this.$store.dispatch('reloadIvr', obj).then(res => {
          if (res.success) {
            this.disabledReload = true
            this.$message({
              type: 'success',
              message: this.$t('configLazyLoad.process.effectiveSuccessfully')
            })
          }
        })
      },
      cancelClick () {
        this.isShowEdit = false
        this.isShowAdd = false
        this.leftSlideVisible = false
      }
    },
    mounted () {
    },
    beforeMount () {
      this.pbxs = this.$store.state.session.account.pbx
      this.search({Account: this.$store.state.session.account.account}, {Account: this.$store.state.session.account.account})
    },
    deactivated () {
      this.oldPBX = this.currentPBX
    },
    activated () {
      if (this.oldPBX !== this.currentPBX) {
        this.refresh()
      }
    }
  }
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .schedule-config__wrapper
    .node-manage
      border 1px solid #e7e7eb
      border-bottom 0px
    .schedule-config__center
      width 100%
      height 100%
      padding 20px
      position relative
      box-sizing border-box
      overflow-y auto
    height calc(100% - 48px)
</style>
